<template>
  <a-modal
    :visible="formVisible"
    :width="1000"
    :title="isEdit ? '编辑' : '新增'"
    @ok="submit"
    @cancel="close"
  >
    <div class="container">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
        <a-space direction="vertical" :size="16">
          <a-card title="基本信息">
            <a-row :gutter="80">
              <a-col :span="8">
                <a-form-item field="name" label="商品名称">
                  <a-input v-model="form.name" placeholder="请填写商品名称" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="category1" label="商品类目">
                  <a-tree-select
                    :data="data"
                    :field-names="{ key: 'id', title: 'name' }"
                    placeholder="请选择商品类目"
                    @change="selectCategory"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="deliveryPlaceId" label="发货地">
                  <a-select
                    v-model="form.deliveryPlaceId"
                    allow-clear
                    :options="deliveryPlaceOptions"
                    placeholder="请选择发货地"
                    :field-names="{ value: 'id', label: 'address' }"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="80">
              <a-col :span="24">
                <a-form-item field="picUrls" label="商品图片">
                  <a-upload
                    v-model="form.picUrls"
                    list-type="picture-card"
                    action="/"
                    image-preview
                    placeholder="请填写商品图片"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="80">
              <a-col :span="8">
                <a-form-item field="freightTemplateId" label="运费模板">
                  <a-select
                    v-model="form.freightTemplateId"
                    allow-clear
                    :options="freightTemplateOptions"
                    placeholder="请选择运费模板"
                    :field-names="{ value: 'id', label: 'name' }"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="saleNum" label="销量">
                  <a-input v-model="form.saleNum" placeholder="请填写" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="shelf" label="是否上架">
                  <a-select
                    v-model="form.shelf"
                    allow-clear
                    :options="NORMAL_STATUS"
                    placeholder="请选择"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="80">
              <a-col :span="16">
                <a-form-item field="ensureServiceIds" label="保障服务">
                  <a-checkbox-group v-model="form.ensureServiceIds">
                    <a-checkbox
                      v-for="{ name, id } in ensureServiceOptions"
                      :key="id"
                      :value="id"
                    >
                      {{ name }}
                    </a-checkbox>
                  </a-checkbox-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="sort" label="排序">
                  <a-input-number
                    v-model="form.sort"
                    :min="0"
                    placeholder="请填写排序"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card title="规格信息">
            <a-form-item field="specType" label="规格类型">
              <a-radio-group v-model="form.specType">
                <a-radio value="0">统一规格</a-radio>
                <a-radio value="1">多规格</a-radio>
              </a-radio-group>
            </a-form-item>
            <div v-if="form.specType === '0'">
              <a-space direction="vertical">
                <a-input-number
                  v-model="goodsSkuOne.salePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                >
                  <template #prepend> 销售价格 </template>
                </a-input-number>
                <a-input-number
                  v-model="goodsSkuOne.salePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                >
                  <template #prepend> 市场价格 </template>
                </a-input-number>
                <a-input-number
                  v-model="goodsSkuOne.salePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                >
                  <template #prepend> 成本价格 </template>
                </a-input-number>
                <a-input-number
                  v-model="goodsSkuOne.salePrice"
                  :min="0"
                  :step="1"
                >
                  <template #prepend> 库存(件) </template>
                </a-input-number>
                <a-input-number
                  v-model="goodsSkuOne.salePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                >
                  <template #prepend> 重量(kg) </template>
                </a-input-number>
                <a-input-number
                  v-model="goodsSkuOne.salePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                >
                  <template #prepend> 体积(m³) </template>
                </a-input-number>
              </a-space>
            </div>
            <div v-else> 开发中 </div>
          </a-card>
          <a-card title="商品描述">
            <QuillEditor
              ref="quill"
              toolbar="full"
              theme="snow"
              content-type="html"
              :disabled="true"
              :content="content"
              :options="options"
              style="width: 100%; height: 250px"
            />
          </a-card>
        </a-space>
      </a-form>
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { computed, ref } from 'vue';
  import { useRequest } from 'vue-request';
  import { useVisible } from '@/hooks/visible';
  import { addGoodsSpu, updateGoodsSpu } from '@/api/mall/goodsspu';
  import { getGoodsCategoryTree } from '@/api/mall/goodscategory';
  import { getFreightTemplateList } from '@/api/mall/freighttemplate';
  import { getDeliveryPlaceList } from '@/api/mall/deliveryplace';
  import { getEnsureServiceList } from '@/api/mall/ensureservice';
  import { NORMAL_STATUS } from '@/api/global';
  import { QuillEditor } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';

  // 编辑器内容
  const content = ref();

  // 编辑器选项
  const options = {
    debug: 'info',
    modules: {
      toolbar: ['bold', 'italic', 'underline'],
    },
    placeholder: '请输入内容~',
    readOnly: false,
    theme: 'snow',
  };

  const formRef = ref();

  const initData = () => {
    return {
      category1: '',
      category2: '',
      createTime: '',
      deliveryPlaceId: '',
      description: '',
      freightTemplateId: '',
      ensureServiceIds: [],
      id: '',
      name: '',
      picUrls: '',
      priceMax: '',
      priceMin: '',
      saleNum: 0,
      shelf: '',
      sort: 0,
      specType: '',
      updateTime: '',
    };
  };

  const rules = {
    category1: [
      {
        required: true,
        message: '商品类目不能为空',
      },
    ],

    createTime: [
      {
        required: true,
        message: '创建时间不能为空',
      },
    ],
    deliveryPlaceId: [
      {
        required: true,
        message: '发货地不能为空',
      },
    ],
    freightTemplateId: [
      {
        required: true,
        message: '运费模板不能为空',
      },
    ],
    name: [
      {
        required: true,
        message: '商品名字不能为空',
      },
    ],
    ensureServiceIds: [
      {
        required: true,
        message: '保障服务不能为空',
      },
    ],
    picUrls: [
      {
        required: true,
        message: '商品图片不能为空',
      },
    ],

    shelf: [
      {
        required: true,
        message: '是否上架不能为空',
      },
    ],

    sort: [
      {
        required: true,
        message: '排序字段不能为空',
      },
    ],

    specType: [
      {
        required: true,
        message: '规格不能为空',
      },
    ],
  };

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void;
    (e: 'refresh'): void;
  }>();

  const form = ref(props.formData);

  const { formVisible, close, open } = useVisible(props, emit);

  const { data } = useRequest(getGoodsCategoryTree);

  const { data: freightTemplateOptions } = useRequest(getFreightTemplateList);
  const { data: ensureServiceOptions } = useRequest(getEnsureServiceList);
  const { data: deliveryPlaceOptions } = useRequest(getDeliveryPlaceList);

  const goodsSkuOne = ref({
    salePrice: 0,
    marketPrice: undefined,
    costPrice: undefined,
    stock: 0,
    weight: undefined,
    volume: undefined,
    enable: '1',
  });

  // 判断是编辑还是新增
  const isEdit = computed(() => !!form.value.id);

  const selectCategory = (e: any) => {
    form.value.category1 = e;
  };

  const submit = async () => {
    formVisible.value = true;
    const validate = await formRef.value.validate();
    if (!validate) {
      if (isEdit.value) {
        await updateGoodsSpu(form.value).then(() => {
          Message.success('修改成功');
        });
      } else {
        await addGoodsSpu(form.value).then(() => {
          Message.success('添加成功');
        });
      }
      form.value = { ...initData };
      formVisible.value = false;
      emit('refresh');
    }
  };

  open(() => {
    const { id } = props.formData;
    if (id) {
      form.value = props.formData;
    } else {
      form.value = initData();
    }
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 40px 20px;
    overflow: hidden;
  }
</style>
